import React, { useState, useRef } from 'react';
import Complete from './complete';
import Headers from './headers';
import Conduct from './conduct';
const Index = () => {
    const inputRef = useRef()
    const [headerValue, setValue] = useState(localStorage.getItem('conduct')?.length && JSON.parse(localStorage.getItem('conduct')) || [])
    const [completeValue, setCompleteValue] = useState(localStorage.getItem('complete')?.length && JSON.parse(localStorage.getItem('complete')) || [])

    // 如果有存localStore就用存的没有就是一个空的
    let values = localStorage.getItem('conduct')?.length && JSON.parse(localStorage.getItem('conduct')) || []
    // 提交任务
    const submit = (e) => {
        values = [...values, { id: `id_${new Date().getTime()}_${parseInt(Math.random() * 10)}`, value: inputRef.current.state.value }]
        localStorage.setItem('conduct', JSON.stringify(values))
        setValue(values)
        inputRef.current.state.value = ''
    }
    // 删除此正在进行的任务
    const ListDelete = (item, index) => {
        const newState = headerValue.filter(_ => _.id !== item.id)
        setValue([...newState])
        localStorage.setItem('conduct', JSON.stringify(newState))
    }
    // 正在进行中的任务提交到完成任务
    const add = (item, index) => {
        setValue(state => {
            const newState = state.filter(_ => _.id !== item.id)
            localStorage.setItem('conduct', JSON.stringify(newState))
            return newState
        })
        setCompleteValue(state => {
            localStorage.setItem('complete', JSON.stringify([...state, item]))
            return [...state, item]
        })

    }
    // 将完成的任务重置到代办中。
    const removeList = item => {
        setValue(state => {
            localStorage.setItem('conduct', JSON.stringify([...state, item]))
            return [...state, item]
        })
        setCompleteValue(state => {
            const newState = state.filter(_ => _.id !== item.id)
            localStorage.setItem('complete', JSON.stringify(newState))
            return newState
        })
    }
    return (
        <div>
            <Headers submit={submit} ref={inputRef} />
            <Conduct headerValue={headerValue} ListDelete={ListDelete} add={add} />
            <Complete completeValue={completeValue} removeList={removeList} />
        </div>
    );
}

export default Index;
